//
//  CheckersAIPlayer.m
//  CheckersGame
//
//  Created by Guest User on 11-12-13.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "CheckersAIPlayer.h"

@implementation CheckersAIPlayer

-(void)letMove {
    iswaiting = NO;
    isdone = YES;
}

-(BOOL) decideMove : (CheckersMove*) move Board: 
(CheckersBoard*) board {
    if (ispaused) return NO;
    int eval;
    if (!iswaiting && !isdone){
        iswaiting = YES;
        timer = [NSTimer scheduledTimerWithTimeInterval:0.3 target:self 
                                           selector:@selector(letMove) 
                                           userInfo:nil repeats:NO];
    }
    if (isdone){
        eval = chbComputeAIResponse(board, &aiSettings, move);
        printf("AI evaluated move with eval=%d\n", eval);
        iswaiting = NO;
        isdone = NO;
        
        return YES;
    }
    return NO;
}

-(id)initWithTimeLimit : (int) timelim 
             depthLimit: (int) depthlim 
            randomNoise: (int) randnoise
             randomCuts: (int) randcut {
    self = [super init];
    if (self) {
        chbInitAISettings(NULL, &aiSettings);
        aiSettings.time_limit = timelim;
        aiSettings.depth_limit = depthlim;
        aiSettings.random_noise = randnoise;
        aiSettings.random_branch_cuts = randcut;
        iswaiting = NO;
        isdone = NO;
    }
    return self;
}
-(id)initDifficulty : (int) difficulty{
    switch (difficulty){
        case 0:
            self = [self initWithTimeLimit: 100
                                depthLimit: 5 
                               randomNoise: 25 
                                randomCuts: 100];
            break;
        case 1:
            self = [self initWithTimeLimit: 100
                                depthLimit: 5 
                               randomNoise: 10 
                                randomCuts: 10];
            break;
        case 2:
            self = [self initWithTimeLimit: 100
                                depthLimit: 7 
                               randomNoise: 10 
                                randomCuts: 10];
            break;
        case 3:
            self = [self initWithTimeLimit: 100000
                                depthLimit: 9 
                               randomNoise: 0 
                                randomCuts: 0];
            break;
        default:
            NSLog(@"Invalid difficulty number in CheckersAIPlayer -> initDifficulty!");
    }
    return self;
}


-(void) setPaused : (BOOL) paused {
    ispaused = paused;
    if (paused)
        [timer invalidate];
    else
        timer = [NSTimer scheduledTimerWithTimeInterval:0.3 target:self 
                                             selector:@selector(letMove) 
                                             userInfo:nil repeats:NO];
}

-(BOOL) needsPieceInteraction {
    return NO;
}


-(void) invalidateNextMove {
    iswaiting = NO;
    isdone = NO;
    [timer invalidate];
}
@end
